<template>
  <div class="wrapper">
    <!-- 头部 -->
    <header>
      <i class="fa fa-arrow-left" @click="goBack"></i>
      <div class="title">{{ businessName }}</div>
      <div class="placeholder"></div>
    </header>

    <!-- 聊天内容区域 -->
    <div class="chat-container">
      <div class="chat-list" ref="chatList">
        <div v-for="(msg, index) in messages" :key="index">
          <!-- 时间显示 -->
          <div class="time-divider">{{ msg.time }}</div>
          <!-- 消息气泡 -->
          <div :class="['message', msg.type === 'send' ? 'message-right' : 'message-left']">
            <img :src="msg.avatar" class="avatar" :alt="msg.name" @error="handleAvatarError">
            <div class="content">
              <!-- 已读状态显示在发送消息气泡左侧 -->
              <div v-if="msg.type === 'send'" class="read-status" :class="{ 'is-read': msg.isRead }">
                {{ msg.isRead ? '已读' : '未读' }}
              </div>
              <div class="text">{{ msg.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部输入框 -->
    <div class="input-container">
      <input 
        type="text" 
        v-model="inputMessage" 
        placeholder="请输入消息..."
        @keyup.enter="handleSend"
      >
      <button @click="handleSend">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { handleAvatarUrl } from '@/utils/imageUtils';
import { useUserInfoStore } from '@/stores/user'; 
import { getMessageHistory, sendMessage, markMessagesAsRead } from '@/api/message';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const chatList = ref(null);
const inputMessage = ref('');
const messages = ref([]);

const user = useUserInfoStore().userInfo;
const receiverId = route.query.receiverId;
const businessName = route.query.businessName;
const businessAvatar = ref(handleAvatarUrl(route.query.businessAvatar));

// 格式化消息列表
const formatMessages = (messageList) => {
  return messageList.map(msg => {
    const messageDate = new Date(msg.createdTime);
    const now = new Date();
    
    // 格式化时间显示
    let timeStr = '';
    const isToday = messageDate.toDateString() === now.toDateString();
    const isYesterday = new Date(now - 86400000).toDateString() === messageDate.toDateString();
    
    if (isToday) {
      timeStr = messageDate.toLocaleTimeString('zh-CN');
    } else if (isYesterday) {
      timeStr = `昨天 ${messageDate.toLocaleTimeString('zh-CN')}`;
    } else {
      timeStr = messageDate.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }

    return {
      type: msg.senderId === user.id ? 'send' : 'receive',
      name: msg.senderId === user.id ? '我' : businessName,
      content: msg.message,
      time: timeStr,
      avatar: handleAvatarUrl(msg.senderId === user.id ? user.avatar : businessAvatar.value),
      isRead: msg.status === 1,
      messageId: msg.id
    };
  });
};

// 获取历史消息
const fetchMessageHistory = async () => {
  try {
    const senderId = route.params.id;
    if (!senderId) {
      console.error('发送者ID无效');
      return;
    }

    const res = await getMessageHistory(senderId, user.id);
    if (res.code === 0) {
      messages.value = formatMessages(res.data);
      scrollToBottom();
    }
  } catch (error) {
    console.error('获取消息历史失败:', error);
    ElMessage.error('获取消息历史失败');
  }
};

// 发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim()) return;

  try {
    const messageContent = inputMessage.value;
    
    if (!receiverId) {
      ElMessage.error('发送失败：接收者ID无效');
      return;
    }

    const res = await sendMessage({
      receiverId: parseInt(receiverId),
      senderId: user.id,
      message: messageContent
    });

    if (res.code === 0) {
      window.sendMessageViaWebSocket({
        type: 'message',
        senderId: user.id,
        receiverId: parseInt(receiverId),
        message: messageContent
      });

      const now = new Date();
      messages.value.push({
        type: 'send',
        content: messageContent,
        time: now.toLocaleTimeString('zh-CN'),
        avatar: handleAvatarUrl(user.avatar),
        isRead: false,
        messageId: res.data
      });
      inputMessage.value = '';
      scrollToBottom();
    }
  } catch (error) {
    ElMessage.error('发送消息失败');
  }
};

// 添加心跳检测
const startHeartbeat = (ws) => {
  const heartbeat = setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({
        command: 'SEND',
        headers: {
          'destination': '/app/heartbeat'
        },
        body: 'ping'
      }));
    } else {
      clearInterval(heartbeat);
      console.log('连接已断开，尝试重连...');
      connectWebSocket();
    }
  }, 30000); // 每30秒发送一次心跳

  return heartbeat;
};

// 建立WebSocket连接
const connectWebSocket = () => {
  const ws = new WebSocket('ws://localhost:10000/ws/chat');
  
  ws.onopen = () => {
    // 直接发送用户ID作为认证信息
    ws.send(JSON.stringify({
      type: 'auth',
      userId: user.id
    }));
  };

  ws.onmessage = (event) => {
    try {
      let messageData;
      try {
        messageData = JSON.parse(event.data);
      } catch (e) {
        messageData = {
          type: 'message',
          message: event.data,
          senderId: receiverId
        };
      }

      // 处理普通消息
      if ((messageData.type === 'message' || !messageData.type) && 
          (messageData.senderId === parseInt(receiverId) || 
           messageData.receiverId === user.id)) {
        
        if (messageData.receiverId === user.id && messageData.senderId) {
          window.sendMessageViaWebSocket({
            type: 'online_status',
            senderId: user.id,
            receiverId: messageData.senderId
          });
        }

        messages.value = [...messages.value, {
          type: messageData.senderId === user.id ? 'send' : 'receive',
          name: messageData.senderId === user.id ? '我' : businessName,
          content: messageData.message || messageData.content,
          time: new Date().toLocaleTimeString(),
          avatar: messageData.senderId === user.id ? handleAvatarUrl(user.avatar) : businessAvatar.value,
          isRead: false
        }];
        scrollToBottom();
      }

      // 处理在线状态消息
      if (messageData.type === 'online_status') {
        if (messageData.senderId === parseInt(receiverId)) {
          messages.value = messages.value.map(msg => ({
            ...msg,
            isRead: msg.type === 'send' ? true : msg.isRead
          }));
        }
      }
    } catch (error) {
      console.error('处理消息失败');
    }
  };

  // 发送消息的方法
  window.sendMessageViaWebSocket = (message) => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify(message));
    }
  };

  // 简化的心跳检测
  const heartbeat = setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: 'ping' }));
    } else {
      clearInterval(heartbeat);
    }
  }, 30000);

  ws.onclose = () => {
    clearInterval(heartbeat);
    setTimeout(() => {
      connectWebSocket();
    }, 3000);
  };

  return ws;
};

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    const chatContainer = document.querySelector('.chat-container');
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  }, 100); // 延迟100毫秒，确保DOM更新完成
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 添加标记，记录是否已经发送过标记已读请求
const hasMarkedAsRead = ref(false);

// 标记消息已读
const markAsRead = async (senderId) => {
  try {
    const actualSenderId = senderId || route.params.id;
    if (!actualSenderId) return;
    
    await markMessagesAsRead(actualSenderId);
    fetchMessageHistory();
  } catch (error) {
    console.error('标记已读失败');
  }
};

// 监听页面可见性变化
const handleVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    markAsRead();
  }
};

onMounted(() => {
  fetchMessageHistory();
  connectWebSocket();
  // 进入页面时标记已读（只标记一次）
  markAsRead();
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

onUnmounted(() => {
  // 组件卸载时重置标记
  hasMarkedAsRead.value = false;
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});

// WebSocket 消息处理
const handleWebSocketMessage = (message) => {
  if (message.senderId === receiverId) {
    messages.value.push({
      type: 'receive',
      content: message.message,
      time: new Date().toLocaleTimeString(),
      avatar: businessAvatar.value,
      isRead: true
    })
    scrollToBottom()
    markAsRead()
  }
}
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3vw 4vw;
  background-color: #ff7043;
  border-bottom: 1px solid #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

header i {
  font-size: 4vw;
  color: #fff;
  width: 8vw;
  cursor: pointer;
}

header .title {
  font-size: 4.5vw;
  font-weight: bold;
  color: #fff;
  flex: 1;
  text-align: center;
  margin: 0 8vw; /* 为两侧留出空间 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

header .placeholder {
  width: 8vw;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 3vw;
  margin-top: 13vw;
  margin-bottom: 15vw;
  height: calc(100vh - 28vw);
}

.chat-list {
  display: flex;
  flex-direction: column;
}

/* 时间分割线样式 */
.time-divider {
  text-align: center;
  font-size: 3vw;
  color: #999;
  margin: 3vw 0;
  position: relative;
}

.message {
  display: flex;
  margin-bottom: 4vw;
  align-items: flex-start;
}

.message-left {
  flex-direction: row;
}

.message-right {
  flex-direction: row-reverse;
}

.avatar {
  width: 10vw;
  height: 10vw;
  border-radius: 50%;
  margin: 0 2vw;
  object-fit: cover; /* 确保头像不变形 */
}

.content {
  position: relative; /* 添加相对定位 */
  max-width: 60%;
}

.message-left .content {
  margin-right: auto;
}

.message-right .content {
  margin-left: auto;
}

.text {
  background-color: #fff;
  padding: 2vw 3vw;
  border-radius: 2vw;
  font-size: 3.8vw;
  line-height: 1.4;
  word-break: break-all;
}

.message-right .text {
  background-color: #ff7043;
  color: #fff;
}

.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 2vw 3vw;
  background-color: #fff;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
}

.input-container input {
  flex: 1;
  height: 9vw;
  border: 1px solid #ddd;
  border-radius: 4vw;
  padding: 0 4vw;
  font-size: 3.8vw;
  margin-right: 3vw;
}

.input-container button {
  width: 20vw;
  height: 9vw;
  background-color: #ff7043;
  color: #fff;
  border: none;
  border-radius: 4vw;
  font-size: 3.8vw;
}

.input-container button:active {
  opacity: 0.8;
}

.input-container input:focus {
  border: 1px solid #b0b0b0;
  outline: none;
  box-shadow: none;
}

.read-status {
  position: absolute;
  left: -8vw; /* 调整位置到气泡左侧 */
  top: 50%;
  transform: translateY(-50%);
  font-size: 2.8vw;
  color: #999;
  white-space: nowrap;
}

.read-status.is-read {
  color: #67C23A;
}

.message-right .content {
  display: flex;
  flex-direction: column;
}

.message-right .text {
  margin-bottom: 0.5vw;
}

.input-area textarea {
  width: 100%;
  height: 100%;
  border: none; /* 移除默认边框 */
  resize: none;
  padding: 10px;
  box-sizing: border-box;
  outline: none; /* 移除默认的聚焦轮廓 */
  background-color: #f5f5f5; /* 可选：添加背景色来区分输入区域 */
}

/* 移除聚焦时的所有边框和效果 */
.input-area textarea:focus {
  border: none;
  outline: none;
  box-shadow: none;
}
</style> 